package com.financing.platform.web;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.financing.platform.dto.PublicActivitiesDTO;
import com.financing.platform.dto.PublicActivitiesPersonDTO;
import com.financing.platform.service.IPublicActivitiesService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.Dict;
import com.financing.platform.util.FileUtil;
import com.financing.platform.util.StringUtil;
import com.financing.platform.vo.PublicActivitiesVO;

@Controller
public class PublicActivitiesAction extends BaseAction{
	
	@Autowired
	private IPublicActivitiesService publicActivitiesServiceImpl;
	
	private @Value("#{settings['fileBaseDir']}") String fileBaseDir;
	
	private @Value("#{settings['publicActivitiesImage']}") String fileDir;
	
	@RequestMapping("/addPublicActivitiesPer.shtml")
	public ModelAndView addPublicActivitiesPer(HttpServletRequest request,
			HttpServletResponse response) {
			request.getSession().setAttribute(Dict.requestID, "addPublicActivitiesPer.shtml");
			return new ModelAndView("addPublicActivities");
	}
	
	@RequestMapping("/addPublicActivities.shtml")
	public ModelAndView addPublicActivities(HttpServletRequest request,
			HttpServletResponse response,@RequestParam(value="activitiesImage", required = false) MultipartFile file,PublicActivitiesDTO publicActivitiesDTO) {
		
			Map<String,Object> resultMap = new HashMap<String,Object>();
			
			//图片路径
			String fileFullPath = new StringBuffer()
											.append(fileDir)
											.append("/")
											.append(StringUtil.dateNowStr("yyyyMMdd")).toString();
			File f = new File(fileBaseDir+fileFullPath);
			
			//如果目录不存在则新建目录
			if(!f.exists()){
				f.mkdirs();
			}
			fileFullPath = new StringBuffer()
								.append(fileFullPath)
								.append("/")
								.append(System.currentTimeMillis())
								.append(file.getOriginalFilename())
								.toString();
			
			DTOdateSet.setCreateInfo(publicActivitiesDTO, request.getSession());
			DTOdateSet.setUpdateInfo(publicActivitiesDTO, request.getSession());
			
			resultMap.put(Dict.result, Dict.result_error);
			
			//检查文件是否合法
			if(checkFile(file)){
				//保存文件
				log.info(fileBaseDir+fileFullPath);
					try {
						FileUtil.saveFile(file,fileBaseDir +fileFullPath);
						publicActivitiesDTO.setActivitiesImageUri(fileFullPath);
					} catch (Exception e) {
						log.error("add public activities error :",e);
					}
			}
			
			publicActivitiesDTO.setActivitiesPublishTime(new Date());
			
			try{
				publicActivitiesServiceImpl.addPublicActivities(publicActivitiesDTO);
				resultMap.put(Dict.result, Dict.result_success);
			}catch(Exception e){
				
			}
			
			return new ModelAndView("addPublicActivities",resultMap);
	}
	
	/**
	 * 
	* @Title: checkFile 
	* @Description: 检查文件类型是否非法
	* @param   file
	* @return boolean   
	* @throws
	 */
	private boolean checkFile(MultipartFile file){
		if(file.isEmpty()){
			return false;
		}
		String fileType = file.getContentType().toLowerCase();
		if(fileType.endsWith("png")||fileType.endsWith("jpeg")||fileType.endsWith("jpg")){
			return true;
		}
		log.error("file type error: "+fileType);
		return false;
	}
	
	@RequestMapping("/publicActivitiesList.shtml")
	public ModelAndView publicActivitiesList(HttpServletRequest request,
			HttpServletResponse response,PublicActivitiesDTO publicActivitiesDTO){
		Map<String,Object> publicActivitiesMap = new HashMap<String,Object>();
		
		request.getSession().setAttribute(Dict.requestID, "publicActivitiesList.shtml");
		
		try {
			List<PublicActivitiesVO>  publicActivitiesList =  publicActivitiesServiceImpl.publicActivitiesList(publicActivitiesDTO);
			publicActivitiesMap.put("publicActivitiesList", publicActivitiesList);
		} catch (SQLException e) {
			log.error("query public activities list error",e);
		}
		publicActivitiesMap.put(Dict.result, request.getParameter(Dict.result));
		return new ModelAndView("publicActivitiesList",publicActivitiesMap);
	}
	
	@RequestMapping("/activitiesNowPerson.shtml")
	@ResponseBody
	public Map<?,?> activitiesNowPerson(HttpServletRequest request,
			HttpServletResponse response,PublicActivitiesPersonDTO publicActivitiesPersonDTO){
		Map<String,Object> activitiesNowPersonList = new HashMap<String,Object>();
		try {
			activitiesNowPersonList.put("publicActivitiesPersonList", publicActivitiesServiceImpl.publicActivitiesPersonList(publicActivitiesPersonDTO));
			activitiesNowPersonList.put(Dict.result,Dict.result_success);
		} catch (SQLException e) {
			log.error("query public activities person error!",e);
			activitiesNowPersonList.put(Dict.result,Dict.result_error);
		}
		return activitiesNowPersonList;
	}
	
	@RequestMapping("/queryPublicActivities.shtml")
	public ModelAndView queryPublicActivities(HttpServletRequest request,
			HttpServletResponse response,PublicActivitiesDTO publicActivitiesDTO){
		Map<String,Object> publicActivitiesMap = new HashMap<String,Object>();
		try {
			publicActivitiesMap.put("publicActivities",publicActivitiesServiceImpl.queryPublicActivities(publicActivitiesDTO));
		} catch (SQLException e) {
			log.error("query public activities error!",e);
		}
		return new ModelAndView("updatePublicActivities",publicActivitiesMap);
	}
	
	@RequestMapping("/updatePublicActivities.shtml")
	public void updatePublicActivities(HttpServletRequest request,
			HttpServletResponse response,PublicActivitiesDTO publicActivitiesDTO,@RequestParam(value="activitiesImage", required = false) MultipartFile file){
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		//图片路径
		String fileFullPath = new StringBuffer()
										.append(fileDir)
										.append("/")
										.append(StringUtil.dateNowStr("yyyyMMdd")).toString();
		File f = new File(fileBaseDir+fileFullPath);
		
		//如果目录不存在则新建目录
		if(!f.exists()){
			f.mkdirs();
		}
		fileFullPath = new StringBuffer()
							.append(fileFullPath)
							.append("/")
							.append(System.currentTimeMillis())
							.append(file.getOriginalFilename())
							.toString();
		
		DTOdateSet.setUpdateInfo(publicActivitiesDTO, request.getSession());
		
		resultMap.put(Dict.result, Dict.result_error);
		
		//检查文件是否合法
		if(checkFile(file)){
			//保存文件
			log.info(fileBaseDir+fileFullPath);
				try {
					FileUtil.saveFile(file,fileBaseDir +fileFullPath);
					publicActivitiesDTO.setActivitiesImageUri(fileFullPath);
				} catch (Exception e) {
					log.error("add public activities error :",e);
					try {
						response.sendRedirect("./publicActivitiesList.shtml?result=0");
					} catch (IOException e1) {
						log.error("send redirect error!",e);
					}
				}
		}
		try{
			publicActivitiesDTO.setActivitiesPublishTime(new Date());
			publicActivitiesServiceImpl.updatePublicActivities(publicActivitiesDTO);
			resultMap.put(Dict.result, Dict.result_success);
		}catch(Exception e){
			log.error("query public activities error!",e);
			try {
				response.sendRedirect("./publicActivitiesList.shtml?result=0");
			} catch (IOException e1) {
				log.error("send redirect error!",e);
			}
		}
		
		try {
			response.sendRedirect("./publicActivitiesList.shtml?result=1");
		} catch (IOException e) {
			log.error("send redirect error!",e);
		}
	}
	
}
